<?php
include 'config.php';

session_start();
//$_SESSION['user_id']
//$_SESSION['user_name']
//$_SESSION['user_lang']

$database =  mysql_connect('localhost',$mysql_user,$mysql_password) or die("error connecting localhost\n");
mysql_select_db('KnowledgeLink') or die("error selecting database\n");
mysql_query("set names 'utf8'");
$current_url=urlencode($_SERVER['REQUEST_URI']);

if((!isset($_SESSION[$site_perfix . 'user_id'])) && (!empty($_COOKIE[$site_perfix . 'user_pwd']))) {
	do_login($_COOKIE[$site_perfix . 'user_name'],$_COOKIE[$site_perfix . 'user_pwd'],$site_perfix,0);
}

//$_user_id
//$_user_name
//$_user_lang
//$_user_theme
if(isset($_SESSION[$site_perfix . 'user_id']))	$_user_id	= $_SESSION[$site_perfix . 'user_id'];
if(isset($_SESSION[$site_perfix . 'user_name']))$_user_name	= $_SESSION[$site_perfix . 'user_name'];
if(isset($_COOKIE[$site_perfix . 'language'])) {
	$_user_lang = $_COOKIE[$site_perfix . 'language'];
	if(isset($_SESSION[$site_perfix . 'user_lang']) && ($_SESSION[$site_perfix . 'user_lang']!=$_user_lang)) {
		$_SESSION[$site_perfix . 'user_lang'] = $_user_lang;
		oj_query("update user set language_display=$_user_lang where id=$_user_id ");
	}
} else if(isset($_SESSION[$site_perfix . 'user_lang']))$_user_lang = $_SESSION[$site_perfix . 'user_lang'];
else $_user_lang=0;
if(isset($_COOKIE[$site_perfix . 'theme']))$_user_theme = $_COOKIE[$site_perfix . 'theme']; else $_user_theme = 'default';
if($_user_theme=='default')$_user_theme='tb_green';

function redirect($location){
	header("Location: " . $location);
	exit();
}

function redirect_error($msg) {
//head没有发送时重定向，否则输出信息后die
	if(headers_sent()) {
		echo "<center><h1>$msg</h1><br/><a href='javascript:history.go(-1);'>Go Back</a></center>";
		include 'footer.php';
		die();
	} else {
		redirect('error.php?msg=' . urlencode($msg));
	}
}

function show_header($title) {
	if(headers_sent())return;
	global $site_title,$_user_theme,$_user_id,$_user_name;
	$page_title=$site_title . ' - ' . $title;
	include 'header.php';
}

function need_login() {
	global $_user_id;
	if(isset($_user_id))return;
	show_header(_d('title_login'));
	redirect_error(_d('err_need_login'));
}

function get_ip() {
	if (getenv('HTTP_CLIENT_IP'))
		$ip = getenv('HTTP_CLIENT_IP');
	else if (getenv('HTTP_X_FORWARDED_FOR'))
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	else if ($_SERVER['REMOTE_ADDR'])
		$ip = $_SERVER['REMOTE_ADDR'];
	else
		$ip = 'unknown';
	return $ip;
}

function get_to_mysql($s){return mysql_real_escape_string(stripslashes($s));}
function get_to_html($s){return htmlspecialchars(stripslashes($s));}
function str_to_mysql($s){return mysql_real_escape_string($s);}
function str_to_html($s){return htmlspecialchars($s);}
function get_to_int($g){ if(isset($g)&&is_numeric($g))return (int)$g; else return 0; }
function get_request($key,$def='') {
	if(!empty($_GET[$key]))return stripslashes($_GET[$key]);
	else if(!empty($_POST[$key]))return stripslashes($_POST[$key]);
	else return $def;
}

function _d($k){
	global $_user_lang,$language_display_array;
	return $language_display_array[$k][$_user_lang];
}

function oj_query($query){
	global $database;
	$ret = mysql_query($query,$database) or die(mysql_error());
	return $ret;
}

function check_checkcode() {
	global $site_perfix;
	return $_SESSION[$site_perfix . 'checkcode']==strtoupper(get_request('checkcode'));
}

function user_id_to_name($user_id){
	if($user_id==0)return 'System'; //系统帐号
	$query = "select name from user where id=$user_id";
	$ret = oj_query($query);
	$row = mysql_fetch_row($ret);
	return $row[0];
}

function user_id_to_name_link($user_id) {
	if($user_id==0)return 'System'; //系统帐号
	$query = "select name from user where id=$user_id";
	$ret = oj_query($query);
	$row = mysql_fetch_row($ret);
	return "<a href='user.php?user_id=$user_id'>" . htmlspecialchars($row[0]) . '</a>';
}

function name_to_user_id($name){
	$query = "select id from user where name='$name'";
	$ret = oj_query($query);
	$row = mysql_fetch_row($ret);
	return $row[0];
}

function get_user_rate($user_id,$node_id) {
	$query="select rate,visit_time from user_rate where user_id=$user_id and node_id=$node_id ";
	$ret=oj_query($query);
	$row=mysql_fetch_row($ret);
	return $row;
}

function set_user_rate($user_id,$node_id,$rate='') {
	if(empty($rate))
		$query="update user_rate set visit_time=now() where user_id=$user_id and node_id=$node_id ";
	else
		$query="update user_rate set rate='$rate', visit_time=now() where user_id=$user_id and node_id=$node_id ";
	$ret=oj_query($query);
}

function rgb_to_html($rgb){
	$ret=dechex($rgb);
	while(strlen($ret)<6)$ret='0' . $ret;
	return '#' . $ret;
}

function update_child_count($node,$delta) {
//所有祖先节点的子节点计数器改变delta值
	$now_parent=$node;
	while($now_parent>=0) {
		$query="select parent,child_count from node where id=$now_parent";
		$ret=oj_query($query);
		$row=mysql_fetch_row($ret);
		if(isset($row[0])) {
			$now_count=$row[1]+$delta;
			$query="update node set child_count=$now_count, child_update_time=now() where id=$now_parent ";
			oj_query($query);
			$now_parent=$row[0];
		} else $now_parent=-1;
	}
}

function easy_insert_node($title,$des,$parent,$create,$question) {
	$query='insert into node (title, description, parent, child_count, create_time, create_id, modify_time, modify_id, has_question, child_update_time) '
		. "values ('$title','$des',$parent,0,now(),$create,now(),$create,'$question',now()) ";
	$ret=oj_query($query);
	$ret=oj_query('select last_insert_id()');
	$row=mysql_fetch_row($ret);
	update_child_count($parent,1);
	return $row[0];
}

function get_special_page_id($name) {
	$query='select id from special_page '
		. "where name='$name' limit 1 ";
	$ret=oj_query($query);
	$row=mysql_fetch_row($ret);
	return $row[0];
}

function get_node_parent_id($id) {
	$ret=oj_query("select parent from node where id=$id limit 1 ");
	$row=mysql_fetch_row($ret);
	return $row[0];
}

function user_gain_point($id,$num,$type) {
	oj_query("update user set $type=$type+$num where id=$id ");
}

function expand_include($current,$des) {
//展开include，不许多次引用，$current是当前id，$des是当前内容
	$included=array(((int)$current)=>1);
	$template=get_special_page_id('Templates');
	while(($pos=strpos($des,'<!--include:'))!==false) {
		$pos_end=strpos($des,'-->',$pos);
		if($pos_end===false)break;
		$sub=substr($des,$pos,$pos_end-$pos);
		sscanf($sub,'<!--include:%d-->',$id);
		$inner='';
		if(!isset($included[(int)$id])) {
			$ret=oj_query("select parent,description from node where id='$id' limit 1 ");
			$row=mysql_fetch_row($ret);
			if($row[0]==$template) {
				$inner=$row[1];
				$pos_end_include=strpos($inner,'<!--end:include-->');
				if($pos_end_include!==false)$inner=substr($inner,0,$pos_end_include);
				$included[(int)$id]=1;
			}
		}
		$des=substr($des,0,$pos) . $inner . substr($des,$pos_end+3);
	}
	return $des;
}

//permission
function permission_node($user_id,$node_id) {
//找父节点，直到遇到根，或者has_question不为no的
//view：查看description、child、question
//add：添加child、question
//modify：修改child、question
//delete：删除子节点（叶）、断开与子节点的联系（成为根）
//add＋delete：移动子节点，两方都要有这个权限
//返回[0]:权限 [1]:权限限制节点 [2]:权限限制节点的父节点
	$now_parent=$node_id;
	//$permission_ret='view'; //总根节点有查看权限
	$next_parent=-1;
	if(empty($user_id))$user_id=-1;
	//根节点权限需在后台设置
	if($now_parent==-1) {
		$query='select level from user_permit '
			. "where node_id=-1 and user_id=$user_id ";
		$ret=oj_query($query);
		$row=mysql_fetch_row($ret);
		if(isset($row[0]))
			$permission_ret=$row[0];
		else
			$permission_ret='view';
		return array(0=>$permission_ret, 1=>$now_parent, 2=>$next_parent);
	}
	//其他节点的权限：
	while(1) {
		$query='select has_question,parent,create_id from node '
			. "where id=$now_parent ";
		$ret=oj_query($query);
		$row=mysql_fetch_row($ret);
		if(!isset($row[0]))break;
		$next_parent=$row[1];
		if($now_parent==$node_id&&$row[2]==$user_id) { //创建者（仅）对该节点有完全权限
			$permission_ret='view,modify,add,delete,super';
			break;
		}
		if($row[0]!='no') {
			if($row[0]=='view')$permission_ret='view';
			if(!isset($user_id))break;
			$query='select level from user_permit '
				. "where node_id=$now_parent and user_id=$user_id ";
			$ret=oj_query($query);
			$row=mysql_fetch_row($ret);
			if(isset($permission_ret))$permission_ret=$permission_ret . ',' . $row[0];
			else $permission_ret=$row[0];
			break;
		}
		if($row[1]<0) {
			if(!isset($user_id))break;
			$query='select level from user_permit '
				. "where node_id=$now_parent and user_id=$user_id ";
			$ret=oj_query($query);
			$row=mysql_fetch_row($ret);
			if(isset($row[0]))
				$permission_ret=$row[0];
			else {
				$permission_ret='view';
				//特殊页面：templates可以添加
				if($now_parent==get_special_page_id('Templates'))$permission_ret .= ',add';
			}
			break;
		}
		$now_parent=$next_parent;
	}
	return array(0=>$permission_ret, 1=>$now_parent, 2=>$next_parent);
}

function permission_give($node_id,$user_id,$level) {
//给一个用户增加指定权限
	$query="select level from user_permit where node_id=$node_id and user_id=$user_id ";
	$ret=oj_query($query);
	$row=mysql_fetch_row($ret);
	if(!isset($row[0])) { //new
		$query="insert into user_permit values ($node_id,$user_id,'$level') ";
		$ret=oj_query($query);
	} else { //update
		$level=$row[0] . ',' . $level;
		$query="update user_permit set level='$level' where node_id=$node_id and user_id=$user_id ";
		$ret=oj_query($query);
	}
}

function permission_check_edit($user_id,$node_id) {
	$permit=permission_node($user_id,$node_id);
	if(!strstr($permit[0],'modify'))
		redirect_error('You are not permitted to edit the node-' . $node_id . '.');
	return $permit;
}

function permission_check_add($user_id,$node_id) {
	$permit=permission_node($user_id,$node_id);
	if(!strstr($permit[0],'add'))
		redirect_error('You are not permitted to add node under node-' . $permit[1] . '.');
	return $permit;
}

function permission_check_delete($user_id,$node_id) {
	$permit=permission_node($user_id,$node_id);
	if(!strstr($permit[0],'delete'))
		redirect_error('You are not permitted to delete the node-' . $node_id . '.');
	return $permit;
}

//permission end

//array function
function a_get_html($ary) {
	//array('-'=>'td','style'=>'color:#f00',...,array(..),array(..))
	foreach($ary as $key=>$val) {
		if(is_int($key)) {
			if(is_array($val))$inner.=a_get_html($val);
			else $inner.=$val;
		} else {
			if($key=='-')$tag=$val;
			else if($val=='')$prop.=" $key=\"$key\"";
			else $prop.=" $key=\"$val\"";
		}
	}
	if(isset($tag))
		return '<' . $tag . $prop . (isset($inner)?">$inner</$tag>":'/>');
	else
		return $inner;
}
function a_draw_html($ary) {
	//array('-'=>'td','style'=>'color:#f00',...,array(..),array(..))
	$first=1;
	foreach($ary as $key=>$val) {
		if(is_int($key)) {
			if($first&&isset($tag)) {
				echo "<$tag$prop>\n";
				$first=0;
			}
			if(is_array($val))a_draw_html($val);
			else echo $val;
		} else {
			if($key=='-')$tag=$val;
			else if($val=='')$prop.=" $key=\"$key\"";
			else $prop.=" $key=\"$val\"";
		}
	}
	if($first&&isset($tag))echo "<$tag$prop/>\n";
	else echo "</$tag>\n";
}
//array end

//draw something
function draw_parents($now_parent) {
	$n=0;
	while($now_parent>=0) {
		$query="select parent,title,child_count from node where id=$now_parent";
		$ret=oj_query($query);
		$row=mysql_fetch_row($ret);
		if(isset($row[0])) {
			$parent[$n][0]=$now_parent;
			$parent[$n][1]=$row[1];
			$parent[$n][2]=$row[2];
			$now_parent=$row[0];
		} else $now_parent=-1;
		$n++;
	}
	for($i=$n-1;$i>=0;$i--) {
		echo "<a href='shownode.php?id={$parent[$i][0]}'>{$parent[$i][1]}({$parent[$i][2]})</a>&nbsp;&gt;&nbsp;";
	}
}

function draw_tablelist_head($cols) {
	echo '<table class="table_list row_hover">';
	echo '<tr>';
	foreach($cols as $key=>$val) {
		if(is_array($val))
			echo "<th {$val[1]}>{$val[0]}</th>";
		else
			echo "<th>$val</th>";
	}
	echo '</tr>';
}

function Draw_Options($ary,$name,$selected,$tag_property=''){
	echo "<select name=\"$name\" $tag_property>";
	foreach($ary as $key=>$val){
		echo "<option value=\"$key\"";
		if($selected==$key&&strlen($selected)==strlen($key))echo ' selected="selected"';
		echo ">$val</option>";
	}
	echo '</select>';
}

function draw_search_box($separate='&nbsp;',$full=1){
	echo '<form action="search.php" method="get">';
	echo _d('search_title') . '<input name="title" value="' . get_to_html($_GET['title']) . '" ' . ($full?'':'size="8"') . ' />&nbsp;';
	echo '<select name="type">';
	echo '<option value="node">' . _d('search_node') . '</option>';
	if($_GET['type']=='group')$sel=' selected';
	echo "<option value='group'$sel>" . _d('search_group') . '</option>';
	echo '</select>' . $separate;
	if($full) {
		echo _d('search_time_start') . '<input name="time_start" value="' . get_to_html($_GET['time_start']) . '"/>' . $separate;
		echo _d('search_time_end')    . '<input name="time_end" value="'   . get_to_html($_GET['time_end'])   . '"/>' . $separate;
	}
	echo '<input type="submit" value="' . _d('search_submit') . '" />';
	echo '</form>';
}

//draw end

function do_login($name,$password,$perfix,$cookie) {
	$login_name = $name;
	$login_pwd  = $password;
	
	if(strlen($login_pwd)!=32)return 'Please make sure that you have enabled the Javascript.';
	
	$query="select password,id,name,language_display from user where name='$login_name' limit 1";
	$ret=oj_query($query);
	$row=mysql_fetch_row($ret);
	if(empty($row[0])||$row[0]!=$login_pwd)return 'Wrong User ID or Password.';
	
	$login_id=$row[1];
	$login_name=$row[2];
	$login_lang=$row[3];
	$_SESSION[$perfix . 'user_name']	= $login_name;
	$_SESSION[$perfix . 'user_id']		= $login_id;
	$_SESSION[$perfix . 'user_lang']	= $login_lang;
	if($cookie!=0) {
		$time_expire=time()+60*60*24*30;
		setcookie($perfix . 'user_name',$login_name,$time_expire);
		setcookie($perfix . 'user_pwd',$login_pwd,$time_expire);
		setcookie($perfix . 'language',$login_lang,$time_expire);
	}
	
	$login_ip=get_ip();
	$query="update user set last_login_ip='$login_ip', last_login_time=now() where id=$login_id";
	oj_query($query);
	
	return 0;
}

?>
